<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getHost,
  getCompanyName,
  addOrUpHost,
  getWarehouseName,
  delHost,
} from "@/api/HostManager";
import { onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";

interface Host {
  id: Number | null;
  sn: string;
  name: string;
  warehouseName: string;
  companyName: string;
  state: string;
  hostModel: string;
  sim: string;
  warehouseId: Number | null;
}
const router = useRouter();

const dialogVisible = ref(false);
const title = ref("");

// 表格数据
const tableData = ref<Array<Host>>([]);
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
  name: "",
});
const total = ref(0);

// 表单数据
const formData = ref<Host>({
  id: null,
  sn: "",
  name: "",
  warehouseName: "",
  companyName: "",
  state: "",
  hostModel: "",
  sim: "",
  warehouseId: null,
});

const stateList = [
  { id: "0", name: "在用" },
  { id: "1", name: "停用" },
];
const companyList = ref([{ id: 0, name: "" }]);
const warehouseList = ref([{ id: 0, name: "" }]);

const companyId = ref();
const ruleFormRef = ref();
// 验证
const rules = {
  warehouseName: [{ required: true, message: "请选仓库", trigger: "change" }],
  warehouseId: [{ required: true, trigger: "change" }],
  companyName: [{ required: true, message: "请选择企业", trigger: "change" }],
  state: [{ required: true, message: "请选择状态", trigger: "change" }],
  sn: [{ required: true, message: "请选输入主机编号", trigger: "blur" }],
  name: [{ required: true, message: "请选输入主机名称", trigger: "blur" }],
  hostModel: [{ required: true, message: "请选输入设备型号", trigger: "blur" }],
  sim: [{ required: true, message: "请选输入sim卡号", trigger: "blur" }],
};

// 更新仓库ID
const selectChange = (selectedName: any) => {
  const selectedWarehouse = warehouseList.value.find(
    (item) => item.name === selectedName
  );

  if (selectedWarehouse) {
    formData.value.warehouseId = selectedWarehouse.id;
  }
};

// 更新企业ID
const selectCompany = (selectedName: any) => {
  const selectedCompany = companyList.value.find(
    (item) => item.name === selectedName
  );

  if (selectedCompany) {
    companyId.value = selectedCompany.id;
  }
  console.log(companyId.value);
  
  
  getWarehouseName(companyId.value)
    .then((res: any) => {
      warehouseList.value = res.data.data;
    })
    .catch(() => {
      ElMessage.error("请联系管理员");
    });
};

// 查询主机信息
const getInfo = () => {
  getHost(pageInfo)
    .then((res: any) => {
      tableData.value = res.data.data.rows;
      total.value = res.data.data.total;
    })
    .catch(() => {
      ElMessage.error("请联系管理员");
    });
};

// 新增按钮
const add = () => {
  dialogVisible.value = true;
  title.value = "新增主机";
  getOtherInfo();
};

// 确认按钮：添加或修改主机
const confirm = () => {
  ruleFormRef.value.validate((valid: any) => {
    if (valid) {
      dialogVisible.value = false;
      addOrUpHost(formData.value)
        .then((res: any) => {
          ElMessage.success(title.value + "成功");
          getInfo();
        })
        .catch(() => {
          ElMessage.error("请联系管理员");
        });
    }
  });
};

// 转到仪表管理
const toInstrument = () => {
  router.push("/homeview/instrumentManagement");
};

// 修改主机
const up = (item: any) => {
  dialogVisible.value = true;
  title.value = "修改主机";
  formData.value = item;
  getOtherInfo();
};

// 删除主机
const del = (id: any) => {
  ElMessageBox.confirm("确定要删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    delHost(id)
      .then((res: any) => {
        getInfo();
        ElMessage.success("删除成功");
      })
      .catch(() => {
        ElMessage.error("请联系管理员");
      });
  });
};

// 停用 启用
const stopOrStart = (item: any, flg: any) => {
  item.state = flg ? "1" : "0";
  addOrUpHost(item)
    .then((res: any) => {
      getInfo();
    })
    .catch(() => {
      ElMessage.error("请联系管理员");
    });
};

// 查询所有企业名称，所有仓库名称
const getOtherInfo = () => {
  getCompanyName()
    .then((res: any) => {
      companyList.value = res.data.data;
    })
    .catch(() => {
      ElMessage.error("请联系管理员");
    });
};

// 监听对话框
watch(dialogVisible, (newValue) => {
  if (newValue == false) {
    ruleFormRef.value.resetFields();
  }
});

// const getInfo = async () => {
//     var { data: { data } } = await getHost(pageInfo);
//     console.log(data);
//     tableData.value = data;
// };

// 挂载函数
onMounted(() => {
  getInfo();
});
</script>

<template>
  <!-- 新增查询 -->
  <div class="div-class" style="margin-bottom: 10px">
    <el-button @click="add" style="margin-right: 10px">新增</el-button>
    <el-input
      v-model="pageInfo.name"
      style="width: 240px"
      placeholder="主机名称"
      @blur="getInfo"
    />
  </div>

  <!-- 表格数据 -->
  <el-table :data="tableData" class="custom-table" empty-text="暂无数据">
    <el-table-column prop="id" label="序号" width="60px">
      <template #default="{ $index }">
        {{ (pageInfo.pageNum - 1) * pageInfo.pageSize + $index + 1 }}
      </template>
    </el-table-column>
    <el-table-column prop="sn" label="编号" />
    <el-table-column prop="name" label="名称" />
    <el-table-column prop="warehouseName" label="仓库名称" />
    <el-table-column prop="companyName" label="企业名称" />
    <el-table-column prop="state" label="状态" width="60px">
      <template #default="scope">
        {{ scope.row.state === "0" ? "在用" : "停用" }}
      </template>
    </el-table-column>
    <el-table-column prop="hostModel" label="设备型号" width="100px" />
    <el-table-column prop="sim" label="sim卡号" />
    <el-table-column label="操作" width="260px">
      <template #default="scope">
        <el-button type="text" @click="toInstrument">仪表管理</el-button>
        <el-button type="text" @click="up(scope.row)">修改</el-button>
        <el-button type="text" @click="del(scope.row.id)">删除</el-button>
        <el-button type="text" @click="stopOrStart(scope.row, 1)"
          >停用</el-button
        >
        <el-button type="text" @click="stopOrStart(scope.row, 0)"
          >启用</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    background
    layout="prev, pager, next"
    :total="total"
    :page-size="pageInfo.pageSize"
    v-model:current-page="pageInfo.pageNum"
    @current-change="getInfo"
    class="pagination"
  />

  <!-- 新增 修改弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    :close-on-click-modal="false"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="auto"
      class="form-class"
    >
      <el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-select
            v-model="formData.companyName"
            placeholder="请选择企业"
            style="width: 196.4px"
            @change="selectCompany"
          >
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select
            v-model="formData.state"
            placeholder="请选择状态"
            style="width: 196.4px"
          >
            <el-option
              v-for="item in stateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form-item>

      <el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-select
            v-model="formData.warehouseName"
            placeholder="请选仓库"
            style="width: 196.4px"
            @change="selectChange"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="仓库id"
          prop="warehouseId"
          :show-message="false"
          :hide-required-asterisk="true"
        >
          <el-input v-model="formData.warehouseId" disabled></el-input>
        </el-form-item>
      </el-form-item>

      <el-form-item>
        <el-form-item label="主机编号" prop="sn">
          <el-input v-model="formData.sn"></el-input>
        </el-form-item>
        <el-form-item label="主机名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-form-item label="设备型号" prop="hostModel">
          <el-input v-model="formData.hostModel"></el-input>
        </el-form-item>
        <el-form-item label="sim卡号" prop="sim">
          <el-input v-model="formData.sim"></el-input>
        </el-form-item>
      </el-form-item>
    </el-form>

    <div class="div-class" style="margin: 50px 15px 0 0">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<style scoped>
.div-class {
  display: flex;
  justify-content: flex-end;
}

.custom-table {
  height: calc(100% - 94px);
}

:deep(.el-table__cell .cell) {
  text-align: center !important;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.form-class {
  padding: 20px 15px 0 15px;
}

:deep(.el-form-item__content) {
  display: flex !important;
  justify-content: space-between !important;
}
</style>